// @file     YCOAServletContainer.groovy
// @author   Mac Radigan
// @version  $Id: YCOAServletContainer.groovy 12 2010-07-26 01:37:14Z mac.radigan $

package ycoa.servlet

import sys.utilities.ResourceManager

import org.mortbay.jetty.*
import org.mortbay.jetty.nio.*
import org.mortbay.jetty.servlet.*
import org.mortbay.jetty.deployer.*
import org.mortbay.jetty.handler.*
import org.mortbay.jetty.webapp.*
import groovy.servlet.*

public class YCOAServletContainer {

  private server = null

  private start(port, webappdir=null) {
    server = new Server(port)
    def handlers = new HandlerCollection()
    if(webappdir) {
      def deployer = new WebAppDeployer()
      deployer.setContexts(server)
      deployer.setWebAppDir(webappdir)
      deployer.setExtract(true)
      deployer.setParentLoaderPriority(false)
      deployer.start()
      def rootContext = new Context(server, "/", Context.SESSIONS)
      rootContext.setResourceBase(".")
      rootContext.addServlet(new ServletHolder(new TemplateServlet()), "*.html")
    } else {
      def webAppContext = new WebAppContext()
      webAppContext.setContextPath("/")
      webAppContext.setResourceBase("webapps")
      webAppContext.setWar(new ResourceManager().getJarFile().getAbsolutePath())
      def handler = new Handler[2]
      handler[0] = webAppContext
      handler[1] = new DefaultHandler()
      handlers.setHandlers(handler)
    }
    server.setHandler(handlers)
    server.setStopAtShutdown(true)
    server.start()
  }

  private stop() {
    server.stop()
  }

  private join() {
    server.join()
  }

}

// *EOF*
